﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Implements;
using Cofe.Core.Interfaces;
using Cofe.Core.Service;
using Cofe.Data;

namespace Cofe.Core
{
    public class ModuleBootStrapper : BootStrapperBase
    {       
        private bool _allowReregister;
        private ICofeService[] _services = null;
        private IRegisterModule[] _modules = null;

        public ModuleBootStrapper(bool allowReregister = false, params IRegisterModule[] modules)
        {
            _allowReregister = allowReregister;
            _modules = modules;
            _services = modules.SelectMany(m => m.Services).ToArray();
        }

        public ModuleBootStrapper(params IRegisterModule[] modules)
            : this(true, modules)
        {

        }

        public override IServiceImporter ConfigureServiceImporter()
        {
            ManualServiceImporter msi = new ManualServiceImporter();
            foreach (var m in _modules)
                m.PreRegister();
            msi.RegisterService(_services);
            return msi;
        }

        public override void Run(params ICofeService[] additionalServices)
        {
            if (!_allowReregister)
                if (CofeServices.ServiceImported)
                    return;
            base.Run(additionalServices);
            foreach (var m in _modules)
                m.PostRegister();
        }
    }
}
